package com.leon.hom.mqtt;

import com.leon.hom.core.config.BrokerConfig;
import com.leon.hom.core.log.Loggers;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

import java.util.UUID;

public class PublishMqttClient {

    /**
     * 设置超时时间
     */
    Integer connectionTimeout = 10;
    /**
     * 会话心跳时间
     */
    Integer keepAliveInterval = 30;
    /**
     * 客户端数组
     */
    MqttClient mqttClient;

    /**
     * QOS
     */
    Integer qos;

    public PublishMqttClient(BrokerConfig brokerConfig) throws Exception {

        MqttClient client = new MqttClient(brokerConfig.getUrl(), UUID.randomUUID().toString(), new MemoryPersistence());
        MqttConnectOptions options = new MqttConnectOptions();
        // 如果想要断线这段时间的数据，要设置成false，并且重连后不用再次订阅，否则不会得到断线时间的数据
        options.setCleanSession(true);
        // 设置连接的用户名
        options.setUserName(brokerConfig.getUsername());
        // 设置连接的密码
        options.setPassword(brokerConfig.getPassword().toCharArray());
        // 设置超时时间 单位为秒
        options.setConnectionTimeout(connectionTimeout);
        // 设置会话心跳时间 单位为秒 服务器会每隔1.5*20秒的时间向客户端发送个消息判断客户端是否在线，但这个方法并没有重连的机制
        options.setKeepAliveInterval(keepAliveInterval);
        // 连接服务器
        client.connect(options);
        this.mqttClient = client;
        this.qos = brokerConfig.getQos();

        Loggers.MQTT.info("Connect MQTT broker: {} , Qos: {}", brokerConfig.getUrl(),brokerConfig.getQos());

    }

    public void close() throws MqttException {
        this.mqttClient.close();
    }


    public void publish(String topic, byte[] bytes) {
        try {
            this.mqttClient.publish(topic, bytes, qos, false);
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }


}
